import path from 'path';
import fs from 'fs-extra'
import ejs from 'ejs'

import { DeepRequired } from '../../types';
import { CONFIG } from '../../types/config';
import { RUN_TEMPLATE_PATH } from '.';

const renderAndWriteFile = (from: string, to: string, options: DeepRequired<CONFIG>) => {
  to = to.replace('.ejs', '')
  const { root, componentRoot } = options
  const componentPath = path.join(root, componentRoot)
  const runJsPath = path.resolve(RUN_TEMPLATE_PATH, 'index.js')
  const extraOptions = {
    relativeEntry: path.relative(runJsPath, componentPath).replace(/\\/g, '/')
  }
  console.log(runJsPath, componentPath)
  const fileContent = fs.readFileSync(from).toString('utf-8')
  const renderContent = ejs.render(fileContent, { ...options, ...extraOptions })
  fs.writeFileSync(to, renderContent)
}

export const copyDir = (dir: string) => {
  fs.ensureDirSync(dir)
}

export const generatorTemplate = (from : string, to: string, options: DeepRequired<CONFIG>) => {
  copyDir(to)
  const templates = fs.readdirSync(from)
  templates.forEach(tmp => {
    const f = path.resolve(from, tmp)
    const t = path.resolve(to, tmp)
    const statObj = fs.statSync(f)
    if (statObj.isDirectory()) {
      generatorTemplate(f, t, options)
    } else {
      renderAndWriteFile(f, t, options)
    }
  })
}
